package com.yu8home.opcua.test;

import com.yu8home.opcua.OpcUAUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.subscriptions.EventFilterBuilder;
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedEventItem;
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedSubscription;
import org.eclipse.milo.opcua.stack.core.Identifiers;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.eclipse.milo.opcua.stack.core.types.structured.EventFilter;

import java.util.concurrent.CountDownLatch;

@Slf4j
public class F {

    public static void main(String[] args) throws Exception {
        OpcUAUtil.getConnect();
        createSubscribe();
        System.in.read();
    }


    public static void createSubscribe() throws Exception {
        final CountDownLatch eventLatch = new CountDownLatch(3);

        ManagedSubscription subscription = ManagedSubscription.create(OpcUAUtil.opcUaClient);

        subscription.addEventChangeListener((eventItems, variants) -> {
            for (int i = 0; i < eventItems.size(); i++) {
                ManagedEventItem eventItem = eventItems.get(i);
                Variant[] eventFieldValues = variants.get(i);

                log.info("标识符：{}", eventItem.getNodeId());
                for (int j = 0; j < eventFieldValues.length; j++) {
                    log.info("变量variant[{}]: {}", j, eventFieldValues[j].getValue());
                }
            }
            eventLatch.countDown();
        });

        EventFilter eventFilter = new EventFilterBuilder()
                .select(Identifiers.BaseEventType, new QualifiedName(2, "EventId"))
                .select(Identifiers.BaseEventType, new QualifiedName(2, "EventType"))
                .select(Identifiers.BaseEventType, new QualifiedName(2, "Severity"))
                .select(Identifiers.BaseEventType, new QualifiedName(2, "Time"))
                .select(Identifiers.BaseEventType, new QualifiedName(2, "Message"))
                .build();

        NodeId nodeId1 = new NodeId(2, "Simulation Examples.Functions.m");
        NodeId nodeId2 = new NodeId(2, "_CustomAlarms.k.Simulation Examples_Functions_k");
        NodeId nodeId3 = new NodeId(2, "k.Simulation Examples_Functions_k.MULTI_LEVEL");

        ManagedEventItem eventItem1 = subscription.createEventItem(nodeId1, eventFilter);
        ManagedEventItem eventItem2 = subscription.createEventItem(nodeId2, eventFilter);
        ManagedEventItem eventItem3 = subscription.createEventItem(nodeId3, eventFilter);
        ManagedEventItem eventItem4 = subscription.createEventItem(Identifiers.Server, eventFilter);
        ManagedEventItem eventItem = subscription.createEventItem(Identifiers.Server, eventFilter);

        eventLatch.await();
        eventItem.delete();
    }

}
